<?php

declare(strict_types=1);

namespace app\common\validate;

use app\common\service\JsonService;
use think\Validate;

class BaseValidate extends Validate
{
    public string $method = 'GET';

    public array $include = [];

    /**
     * @notes 设置请求方式
     */
    public function post(array $include = [])
    {
        if (!$this->request->isPost()) {
            JsonService::throw('请求方式错误，请使用post请求方式');
        }
        $this->method = 'POST';
        $this->include = $include;
        return $this;
    }

    /**
     * @notes 设置请求方式
     */
    public function get(array $include = [])
    {
        if (!$this->request->isGet()) {
            JsonService::throw('请求方式错误，请使用get请求方式');
        }
        $this->include = $include;
        return $this;
    }

    /**
     * @notes 过滤不需要的参数
     * @param array $params 接收的参数
     * @param array $exclude 不需要的参数列表
     * @return array 过滤后的参数
     */
    public function filterParams(array $params, array $include): array
    {
        $includeArr = conver_to_key_value_arr($include);
        $mergedArr = $params+$includeArr;
        // 过滤值为null的键
        return array_filter($mergedArr,function ($value){
            return $value !== null;
        });
    }


    /**
     * @notes 切面验证接收到的参数
     * @param null $scene 场景验证
     * @param array $validateData 验证参数，可追加和覆盖掉接收的参数
     * @return array
     */
    public function goCheck($scene = null, array $validateData = [], array $include = []): array
    {
        //接收参数
        if ($this->method == 'GET') {
            $params = request()->get();
        } else {
            $params = request()->post();
        }
        //合并验证参数
        $params = array_merge($params, $validateData);
        // 过滤不需要的参数
        $params = $this->filterParams($params, $this->include);
        //场景
        if ($scene) {
            $result = $this->scene($scene)->check($params);
        } else {
            $result = $this->check($params);
        }

        if (!$result) {
            $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
            JsonService::throw($exception);
        }
        // 3.成功返回数据
        return $params;
    }
}